package com.example.radiobutton_checkbox;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class Radiobutton extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radiobutton);
        RadioGroup radgroup = (RadioGroup) findViewById(R.id.radioGroup);
        Button btnpost = (Button) findViewById(R.id.btnpost);
        //第一种获得单选按钮值的方法
        //为radioGroup设置一个监听器:setOnCheckedChanged()
        radgroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radbtn = (RadioButton) findViewById(checkedId);
                Toast.makeText(getApplicationContext(), "按钮组值发生改变,你选了" + radbtn.getText(), Toast.LENGTH_LONG).show();
            }
        });
        //为radioGroup设置一个监听器:setOnCheckedChanged()
        btnpost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < radgroup.getChildCount(); i++) {// 获得按钮组中的单选按钮的数目；
                    RadioButton rd = (RadioButton) radgroup.getChildAt(i);//根据索引值获取我们的单选按钮
                    if (rd.isChecked()) {//判断按钮是否选中
                        Toast.makeText(getApplicationContext(), "点击提交按钮,获取你选择的是:" + rd.getText()+"", Toast.LENGTH_LONG).show();
                        break;
                    }
                }
            }
        });

    }
}